package com.haozi.ehub.core.model;

import com.haozi.ehub.entity.entities.AuthInfo;
import com.haozi.ehub.entity.entities.JwtUserInfo;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 用户model
 * @author ：terry
 * @date ：Created in 2020/6/15 9:46
 * @version: 1.0
 */
@Data
public class User implements UserDetails, Serializable {
    private static final long serialVersionUID = 1L;
    private String id;
    private String username;
    private String password;
    private String encryptName;
    private String token;
    private Collection<? extends GrantedAuthority> authorities;

    public User() {
    }

    public User(JwtUserInfo jwtUserInfo) {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        if(jwtUserInfo.getRoleList()!=null && jwtUserInfo.getRoleList().size()>0){
            jwtUserInfo.getRoleList().forEach(roleInfo -> {
                authorityList.add(roleInfo::getRoleCode);
                List<AuthInfo> authInfoList = roleInfo.getAuthInfoList();
                if (authInfoList!=null && authInfoList.size()>0) {
                    authInfoList.forEach(authInfo -> {
                        if (authInfo != null) {
                            authorityList.add(authInfo::getAuthCode);
                        }
                    });
                }
            });
        }
        this.id = jwtUserInfo.getUserId();
        this.username = jwtUserInfo.getUserName();
        this.password = jwtUserInfo.getPassword();
        this.encryptName = jwtUserInfo.getEncryptName();
        this.token = jwtUserInfo.getToken();
        this.authorities = authorityList;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
